<template>
  <el-card class="box-card">
    <el-form inline>
      <el-form-item>
        <el-input placeholder="用户名" v-model="input" />
      </el-form-item>

      <el-button type="primary" icon="el-icon-search" @click="searchKeyword"
        >查询</el-button
      >
      <el-button type="default" @click="clear">清空</el-button>
    </el-form>
    <div style="margin-bottom: 20px">
      <el-button type="primary" @click="showAdd">添 加</el-button>
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
    </div>
    <el-table
      style="width: 100%"
      @selection-change="handleSelectionChange"
      :data="userList"
      border
    >
      <el-table-column type="selection" width="38"> </el-table-column>
      <el-table-column label="序号" width="79" type="index"> </el-table-column>
      <el-table-column prop="username" label="用户名" width="149">
      </el-table-column>
      <el-table-column prop="nickName" label="用户昵称" width="181">
      </el-table-column>
      <el-table-column prop="roleName" label="角色列表" width="199">
      </el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间" width="179">
      </el-table-column>
      <el-table-column prop="gmtModified" label="更新时间" width="179">
      </el-table-column>
      <el-table-column prop="" label="操作" width="199" align="center">
        <template slot-scope="{ row }">
          <el-button
            type="info"
            size="mini"
            icon="el-icon-user-solid"
            title="分配角色"
            @click="setUser(row)"
          />
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            title="修改用户"
            @click="showEdit(row)"
          />
          <el-popconfirm
            :title="`确定删除 ${row.username} 吗?`"
            @confirm="removeUser(row.id)"
            v-show="(confirm = true)"
          >
            <el-button
              style="margin-left: 10px"
              slot="reference"
              type="danger"
              size="mini"
              icon="el-icon-delete"
              title="删除用户"
              @click="confirm = true"
            />
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 10px"
      @size-change="setSize"
      @current-change="setCurrent"
      :current-page="current"
      :page-sizes="[3, 6, 9]"
      :page-size="pageSize"
      layout="prev, pager,next, jumper,->, sizes,total "
      :total="total"
    >
    </el-pagination>
    <el-dialog
      :title="user.id ? '修改用户' : '添加用户'"
      :visible.sync="dialogUserVisible"
    >
      <el-form
        ref="userForm"
        :model="user"
        :rules="userRules"
        label-width="120px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username" />
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="user.nickName" />
        </el-form-item>

        <el-form-item v-if="!user.id" label="用户密码" prop="password">
          <el-input v-model="user.password" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addOrUpdate">确 定</el-button>
      </div>
    </el-dialog>
    <UserModel ref="userModel"></UserModel>
  </el-card>
</template>

<script>
import userApi from "@/api/mine/user";
import { Message } from "element-ui";
import UserModel from "./components/UserModel.vue";
export default {
  name: "User",
  data() {
    return {
      userList: [],
      total: 0,
      current: 1,
      pageSize: 3,
      multipleSelection: [],
      input: "",
      dialogUserVisible: false,
      user: {
        username: "",
        password: "",
        nickName: "",
      },
      userRules: {
        // 用户添加/修改表单的校验规则
        username: [
          { required: true, message: "用户名必须输入" },
          { min: 4, message: "用户名不能小于4位" },
        ],
        password: [{ required: true, validator: this.validatePassword }],
      },
      confirm: false,
    };
  },
  components: {
    UserModel,
  },
  methods: {
    async getUserList() {
      try {
        let { data } = await userApi.getUser(
          this.current,
          this.pageSize,
          this.input
        );
        this.userList = data.items;
        this.total = data.total;
      } catch (error) {
        console.log(error);
      }
    },
    // 修改当前页
    setCurrent(current) {
      this.current = current;
    },
    setSize(pageSize) {
      this.pageSize = pageSize;
    },
    handleSelectionChange(val) {
      this.multipleSelection = [...val];
    },
    searchKeyword() {
      if (!this.input.value) this.getUserList();
    },
    clear() {
      this.input = "";
      this.getUserList();
    },
    //   显示添加模态框
    showAdd() {
      this.user = {};
      this.dialogUserVisible = true;
    },
    showEdit(item) {
      this.dialogUserVisible = true;
      this.user = item;
    },
    // 取消保存
    cancel() {
      this.dialogUserVisible = false;
      this.user = {};
    },
    // 保存或更新用户
    async addOrUpdate(user) {
      try {
        if (this.user.id) {
          await userApi.update(this.user);
        } else {
          await userApi.add(this.user);
        }
        this.$message.success("保存成功!");
        this.getUserList();
        this.user = {};
      } catch (error) {
        console.log(error);
      } finally {
        this.dialogUserVisible = false;
      }
    },
    // 删除一条
    async removeUser(id) {
      try {
        await userApi.removeById(id);
        this.$message.success("删除成功");
        this.getUserList();
      } catch (error) {
        console.log(error);
      }
    },
    // 批量删除
    async batchDelete() {
      try {
        await this.$alert("确定删除吗", "警告", {
          confirmButtonText: "确定",
          showCancelButton: "取消",
        });
        await Promise.all(
          this.multipleSelection.map(async (item) => {
            await userApi.removeById(item.id);
          })
        );
        Message.success("删除成功");
        this.getUserList();
      } catch (error) {
        console.log(error);
      }
    },
    setUser(item) {
      this.$refs.userModel.assign = item;
      this.$refs.userModel.dialogFormVisible = true;
    },
  },
  mounted() {
    this.$bus.$on("getUserList", this.getUserList);
    this.getUserList();
  },
  computed: {
    cpChange() {
      let { current, pageSize } = this;
      return {
        current,
        pageSize,
      };
    },
  },
  watch: {
    cpChange() {
      //   console.log(11);
      this.getUserList();
    },
  },
};
</script>

<style scoped></style>
